# -*- coding: utf-8 -*-

# Define here the models for your spider middleware
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/spider-middleware.html

from scrapy import signals
from scrapy.http import HtmlResponse
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
#引入cnblog_spider.py的parse方法

class CnblogSpiderMiddleware(object):
    # Not all methods need to be defined. If a method is not defined,
    # scrapy acts as if the spider middleware does not modify the
    # passed objects.

    @classmethod
    def from_crawler(cls, crawler):
        # This method is used by Scrapy to create your spiders.
        s = cls()
        crawler.signals.connect(s.spider_opened, signal=signals.spider_opened)
        return s

    # def __init__(self):
    #        # 这里以Chrome浏览器为例，初始化ChromeDriver
    #        self.driver = webdriver.Chrome()

    def process_spider_input(self, response, spider):
        # Called for each response that goes through the spider
        # middleware and into the spider.

        # Should return None or raise an exception.
        return None

    def process_spider_output(self, response, result, spider):
        # Called with the results returned from the Spider, after
        # it has processed the response.

        # Must return an iterable of Request, dict or Item objects.
        for i in result:
            yield i

    def process_spider_exception(self, response, exception, spider):
        # Called when a spider or process_spider_input() method
        # (from other spider middleware) raises an exception.

        # Should return either None or an iterable of Response, dict
        # or Item objects.
        pass

    def process_start_requests(self, start_requests, spider):
        # Called with the start requests of the spider, and works
        # similarly to the process_spider_output() method, except
        # that it doesn’t have a response associated.

        # Must return only requests (not items).
        
                # 可以根据页面加载情况调整等待时间，确保动态内容加载完成
        for request in start_requests:
            spider.driver.get(request.url)
            WebDriverWait(spider.driver, 10).until(
                EC.presence_of_element_located((By.CSS_SELECTOR, 'span.lbx a[href]'))
            )
            html = spider.driver.page_source
            response = HtmlResponse(url=request.url, body=html, encoding='utf-8', request=request)
            # 手动调用解析函数处理响应
            yield from spider.parse(response)

            

    def spider_opened(self, spider):
        spider.logger.info('Spider opened: %s' % spider.name)
